package com.example.gobang2.controller;

import com.example.gobang2.mapper.UserMapper;
import com.example.gobang2.model.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(HttpServletRequest req){
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userMapper.selectByName(username);
        if(user==null){
            System.out.println("[UserController] 用户不存在！userName="+user.getUsername());
            return null;
        }
       if(!password.equals(user.getPassword())){
           System.out.println("[UserController] 用户密码错误！userName="+user.getUsername());
           return new User();
       }
       HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
       return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password){
        User user = null;
        try{
            user = new User();
            user.setPassword(password);
            user.setUsername(username);
            userMapper.insert(user);
            System.out.println("[UserController] 用户注册成功！userName="+username+",password="+password);
        }catch (org.springframework.dao.DuplicateKeyException e ){
            user = new User();
        }
        return user;
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object userInfo(HttpServletRequest req){
        HttpSession session = req.getSession();
        if(session==null)
            return new User();
        User user = (User) session.getAttribute("user");
        if(user==null){
            return new User();
        }
        return user;
    }

}
